import React from 'react';

import logo from '@/assets/logo.png';

import './index.scss';
import {useStore} from '@/store';
import { useNavigate } from 'react-router-dom'

import {Button, Card, Checkbox, Form, Input, message} from "antd";

/**
 * 登录路由组件
 * @returns {JSX.Element}
 * @constructor
 */
function Login() {

  const navigate = useNavigate()
  const { loginStore } = useStore()

  /**
   * 表单提交成功的数据
   * @param values
   */
  async function onFinish(values) {
    const { mobile, code } = values
    try {
      // 请求登录数据
      await loginStore.login({
        mobile, code
      })
      // 跳转页面
      navigate('/')
      message.success('登陆成功！')
    } catch (e) {
      message.error(e.response?.data?.message || '登录失败！')
    }
  }

  return (
    <div className="login">
      <Card className="login-container">
        <img className="login-logo" src={logo} alt="" />
        {/*登录表单验证*/}
        <Form
          // 根据name指定默认值
          initialValues={{
            mobile: '13811111111',
            code: '246810',
            remember: true
          }}
          // Form中需要的事件
          validateTrigger={[
            'onBlur',
            'onChange'
          ]}
          onFinish={onFinish}
        >
          {/*手机号验证*/}
          <Form.Item
            name="mobile"
            rules={[
              {
                required: true,
                message: '请输入手机号!',
              },
              {
                pattern: /^1[3-9]\d{9}$/,
                message: '手机号码格式不对',
                validateTrigger: 'onBlur'
              }
            ]}
          >
            <Input size="large" placeholder="请输入手机号" />
          </Form.Item>
          {/*验证码验证*/}
          <Form.Item
            name="code"
            rules={[
              {
                required: true,
                message: '请输入验证码!',
              },
              {
                len: 6,
                message: '请输入六位验证码!',
                validateTrigger: 'onBlur'
              }
            ]}
          >
            <Input size="large" placeholder="请输入验证码" />
          </Form.Item>
          {/*用户协议和隐私条款*/}
          <Form.Item
            name="remember"
            valuePropName="checked"
          >
            <Checkbox className="login-checkbox-label">
              我已阅读并同意「用户协议」和「隐私条款」
            </Checkbox>
          </Form.Item>
          {/*登录按钮*/}
          <Form.Item>
            <Button type="primary" htmlType="submit" size="large" block>
              登录
            </Button>
          </Form.Item>
        </Form>
      </Card>
    </div>
  );
}

export default Login;